package com.jiliason.segmentation.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Map;

public class JsonUtil {
    private static final ObjectMapper JsonMapper =
            // 没有对应字段不抛错
            new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                    // java对象时忽略null的字段
                    .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    public static String pojoToJson(Object pojo) {
        try {
            return JsonMapper.writeValueAsString(pojo);
        } catch (JsonProcessingException ignored) {}
        return null;
    }

    public static <T> T mapToPojo(Map<String, Object> map, Class<T> pojoClazz) {
        try {
            T t;
            // 只考虑无参构造
            Constructor<?> constructor = pojoClazz.getDeclaredConstructor();
            t = (T) constructor.newInstance();
            Field[] fields = pojoClazz.getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if(Modifier.isStatic(mod) || Modifier.isFinal(mod)) continue;
                field.setAccessible(true);
                field.set(t, map.get(field.getName()));
            }
            return t;
        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException ignored) {
        }
        return null;
    }

}
